package com.bookstore.framework.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Spring Security配置
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 配置Spring Security忽略的URL
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 设置不拦截规则
        web.ignoring().antMatchers(
            "/swagger-ui.html",
            "/swagger-ui/**",
            "/swagger-resources/**",
            "/v2/api-docs/**",
            "/v3/api-docs/**",
            "/webjars/**",
            "/doc.html",
            "/favicon.ico",
            "/error",
            // 考虑context-path的情况
            "/api/swagger-ui.html",
            "/api/swagger-ui/**",
            "/api/swagger-resources/**",
            "/api/v2/api-docs/**",
            "/api/v3/api-docs/**",
            "/api/webjars/**",
            "/api/doc.html"
        );
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()  // 禁用CSRF
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用JWT，不需要session
            .and()
            .authorizeRequests()
            // 允许Swagger/Knife4j相关路径匿名访问
            .antMatchers("/swagger-ui.html",
                         "/swagger-ui/**",
                         "/swagger-resources/**",
                         "/v2/api-docs",
                         "/v3/api-docs",
                         "/webjars/**",
                         "/doc.html").permitAll()
            // 允许登录接口匿名访问
            .antMatchers("/auth/login", "/auth/register").permitAll()
            // 允许测试接口匿名访问
            .antMatchers("/", "/swagger-test/**", "/health").permitAll()
            // 其他所有请求需要认证
            .anyRequest().authenticated();

        // 禁用默认登录页面
        http.formLogin().disable();
        http.httpBasic().disable();
    }
}